<?php
namespace app\web\controller;

use app\model\Util; 
use app\model\Theme; 
use app\model\Sms as Sms_mod;

use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Cell;

class Sms extends Base
{
    public function Sms()
    {
/**
 * Author: cbw
 * Desc: 易宣短信服务
 * Time: 2022/12/5 09:40
 * Email: 17854288794@163.com
 */
global $_G,$_S,$_C,$_P;
$themeid = intval($_P['themeid']);
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
//if (DOMAIN1 == "www.yixuan.net") {
//    return_msg('对接服务器未开启短信功能');
//}

$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
$system = $_G['system'];
$do = 'sms';
$op = isset($_P['op'])?$_P['op']:'display';
$ac = isset($_P['ac'])?$_P['ac']:'';
$trade_status =- isset($_P['trade_status'])?$_P['trade_status']:'';
$brand = Sms_mod::getSignature($system,$themeid);

if (empty($_P['createtime']['start'])){
    $starttime = db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
    $start_day =  date('Y-m-d H:i:s',$starttime);
}else{
    $starttime = strtotime($_P['createtime']['start']);
    $start_day = $_P['createtime']['start'];
}
if (empty($_P['createtime']['end'])){
    $endtime = time();
    $end_day = date("Y-m-d H:i:s",$endtime);
}else{
    $endtime = strtotime($_P['createtime']['end']);
    $end_day = $_P['createtime']['end'];
}

//初始化检测 创建数据表

//删除快捷发送手机号中的重复记录仅保留一个
Sms_mod::deleteRepeatQuickMobileItem();
//检测正在审核的短信--修改状态
Sms_mod::llReport($system);
//采集系统手机号数据来源
$sms_system_mobile_type = [
    ['title'=>'订单中-已支付用户+线下订单','val'=>1,'type'=>'default'],
    ['title'=>'订单中-未支付用户','val'=>2,'type'=>'default'],
];
if ($config['maxcountall']>1){
    $sms_system_mobile_type = [
        ['title'=>'订单中-已支付用户+线下订单','val'=>1,'type'=>'default'],
        ['title'=>'订单中-未支付用户','val'=>2,'type'=>'default'],
        ['title'=>'订单中-所有团长','val'=>3,'type'=>'default'],
        ['title'=>'订单中-所有团员','val'=>4,'type'=>'default'],
        ['title'=>'订单中-拼团成功的团长','val'=>5,'type'=>'default'],
        ['title'=>'订单中-拼团成功的团员','val'=>6,'type'=>'default'],
        ['title'=>'订单中-拼团中的团长','val'=>7,'type'=>'default'],
        ['title'=>'订单中-拼团中的团员','val'=>8,'type'=>'default'],
    ];
}
if (db_tableexists(t_sms_config)){
    $sms_config = db_get(t_sms_config,['themeid'=>$themeid,'module_name'=>MODULE_NAME]);
    $config = array_merge($config,(array)$sms_config);
}

if ($_G['isSuperAdmin'] && $op!='betch_ali' && $op!='template_queue_wait_total' && $op!='queue_sms_template_send' && $op!='delete_queue_sms'
    && $op!='template_wait_total' && $op!='quick_sms_send'){
    //更新到达状态
    Sms_mod::reportSms($themeid);
    //执行队列
    if ($config['open_yx_sms']==1){
        Sms_mod::sendSmsQueue($themeid,$config,$system);
    }
}
$page_index = max(1,intval($_P['page']));
$page_size = 50;
$page_start = ($page_index-1)*$page_size;
$type = isset($_P['type'])?$_P['type']:'';
$remark = isset($_P['remark'])?$_P['remark']:'';
$search_data = isset($_P['search_data'])?$_P['search_data']:'';
if ($search_data){
    $search_data = '%'.$search_data.'%';
}
$has_limit_sms = Sms_mod::getUsedSmsTotal($themeid,'',5);


$used_sms =Sms_mod::getUsedSmsTotal($themeid);
$used_amount = max(0,0.1*$used_sms);
$module_name =MODULE_NAME;
$open_yx_sms = $config['open_yx_sms'];
$has_sms_config = db_get(t_sms_config,['themeid'=>$themeid,'module_name'=>MODULE_NAME]);
if ($op=='display' && !$has_sms_config){
    $op = 'sms_config';
    $res = Sms_mod::formatUpdateSmsConfig($themeid,$config,$system);
}else{
    $open_yx_sms = $has_sms_config['open_yx_sms'];
}

$indexurl = $config['indexurl'];
if($indexurl){
    $indexurl_array = parse_url($indexurl);
    $index_url = $indexurl_array['host'].$indexurl_array['path'];
}else{
    $index_url = '';
}

//短信配置
if ($op=='sms_config'){
    $sms_config = [];
    if ($has_sms_config){
        $sms_config = $has_sms_config;
    }
    $sms_notice_signname = $has_sms_config['sms_notice_signname'];
    if($system['ruanjian']==5||$config['isicon']==3 || $system['is_mystery_boxes']>0 || $system['is_mystery_boxes_feichi']>0||$system['lottery']==1||$system['is_mystery_boxes']>0 || $system['is_mystery_boxes_feichi']>0) {
        $sms_notice_signname_length = (int)mb_strlen($_P['sms_notice_signname'], 'UTF8');
        if ($sms_notice_signname_length > 7) {
            return show_json(0, ['msg' => '短信通知名称最大只支持7个字符']);
        }
        $jubf = mb_substr($theme['jubf'],0,4).':';
    }else{
        $jubf = $theme['jubf'].':';
    }


    $action = 10;
    if ($_G['ispost']){

        Sms_mod::installSql();
        $res = Sms_mod::formatUpdateSmsConfig($themeid, $config, $system, $_P, $action);
        if (!$res) {
            return show_json(0, ['msg' => '操作失败']);
        } else {
            return show_json(1, ['msg' => '操作成功']);
        }
    }
    $return_clicent = get_defined_vars();
return view('/sms/sms_config', $return_clicent);
}
//发送日志
if ($op=='display'){
    $action = 6;
    $status = isset($_P['status'])?$_P['status']:0;
    $tradeId = $_P['tradeId'];
    if (!db_tableexists(t_sms_send_log)) {
        $return_clicent = get_defined_vars();
return view('/sms/sms', $return_clicent);
        die;
    }
    $template_list  = Sms_mod::getSmsTemplateCountByType($themeid,$system);
    $trade_status_list  = Sms_mod::getTradeStatusCount($themeid);
    $status_list  = Sms_mod::getStatusCount($themeid,$tradeId);
    $name_arr = getKeynameArray();
    $get_template_list = db_getall(t_sms_template,['themeid'=>$themeid,'module_name'=>MODULE_NAME]);
    if ($get_template_list){
        foreach ($get_template_list as $tk => $tv){
            $get_type = 'sms_diy_'.$tv['id'];
            $name_arr[$get_type] = $tv['remark'];
        }
    }
    $type_list = Sms_mod::getSmsTemplateArr($system,$config,'all',0,false,true);
    if ($status<0){
        if ($status==-1){
            //审核
            $page_total = Sms_mod::getTemplateSmsData(0,0,true);
            $list =       Sms_mod::getTemplateSmsData($page_start,$page_size,false);
        }else{
            //待发送队列数据
            $page_total = Sms_mod::getSmsQueueList($themeid,0,0,true);
            $list =       Sms_mod::getSmsQueueList($themeid,$page_start,$page_size,false);
        }
    }else{
        $page_total = Sms_mod::getSmsLog($themeid, $search_data, 0, 0, $start_day, $end_day, $status, $type, true, $trade_status,$tradeId);
        $list = Sms_mod::getSmsLog($themeid, $search_data, $page_start, $page_size, $start_day, $end_day, $status, $type, false, $trade_status,$tradeId);
    }

    foreach ($list as $k => $v){
        $list[$k]['sms_length'] = mb_strlen('【'.$brand.'】'.$v['content'],'UTF8');
        $kk = ($page_index-1)*$page_size;
        $list[$k]['id'] = $page_total-($k+$kk);
    }
    $total = $page_total;
    //导出
    if (checksubmit('export_submit', true)){
        $count = $total;
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'mobile' => '手机','username' => '姓名',
            'nickname' => '微信昵称','type' => '场景',  'content'=>'短信内容',
            'status' => '发送状态',
            'sms_num' => '条数',
            'sms_num_amount' => '费用',
            'admin_name' => '操作人',
            'ip' => '操作ip',
            'created_at'=>'发送时间'
        );
        if ($_G['isSuperAdmin']){
//            $header['trade_status']= '送达状态';
        }
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {
        $ex_page = max(intval($_P['ex_page']),1);
            $page_start = ($ex_page - 1) * $page_limit;
            $list = Sms_mod::getSmsLog($themeid,$search_data,$page_start,$page_limit,$start_day,$end_day,$status,$type,false,$trade_status);
            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {

                        switch ($row['status']){
                            case 1:
                                $row['status'] = '发送成功';
                                break;
                            case 2:
                                $row['status'] = '发送失败';
                                break;
                            default:
                                $row['status'] = '未知状态';
                                break;
                        }
                        if ($row['type']==''){
                            $row['type'] = '自定义模版';
                        }
                        if ($row['type']!='diy'){
                            $row['type'] = $type_list[$row['type']]['name'];
                        }
                        if ($row['type']=='diy'){
                            $export_template_item= db_get(t_sms_template,['id'=>$row['templateId']]);
                            if ($export_template_item && $export_template_item['remark']){
                                $row['type'] = $export_template_item['remark'];
                            }else{
                                $row['type'] = '自定义模版';
                            }
                        }
                        if ($row['status']=='发送成功'){
                            $row['sms_num_amount'] = $row['sms_num']/10;
                            $row['content'] = '【'.$brand.'】'.$row['content'];
                        }else{
                            $row['sms_num_amount'] = 0;
                            $row['content'] = '【'.$brand.'】'.$row['content'];
                        }

                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        if (isset($data)){
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
            }
       //}
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'短信发送明细',$themeid,$is_end,$pagesize);
    }

    $pager = pagination($page_total,$page_index,$page_size);

    $return_clicent = get_defined_vars();
return view('/sms/sms', $return_clicent);
}
//补发
if ($op=='reissue'){
    //将发送日志中status=5的记录干掉
    db_delete(t_sms_send_log,['themeid'=>$themeid,'status'=>5]);
    //执行队列
    Sms_mod::sendSmsQueue($themeid,$config,$system,true);
}
//短信模版
if ($op=='template_list'){
    Sms_mod::autoCheckSmsTemplate($module_name,$system,'',$_G['username']);
    $action = 3;
    $template_status = isset($_P['template_status'])?$_P['template_status']:-1;
    $status_list  = Sms_mod::getSmsTemplateStatusCount($themeid);
    $can_send_template_total = Sms_mod::getCanSendTemplateTotal($themeid);
    $page_total = Sms_mod::getSmsTemplate($themeid,$search_data,0,0,$template_status,'',true);
    $list =       Sms_mod::getSmsTemplate($themeid,$search_data,$page_start,$page_size,$template_status,'',false);
    foreach ($list as $k => $val){
        //判断是否存在待发送手机号任务
        if ($val['template_status']==1){
            $mobile_list = db_getall(t_sms_quick_mobile,['themeid'=>$themeid,'template_id'=>$val['id']],'',[],[0,1000]);
            if (count($mobile_list)>0){
                //先取1000
                $list[$k]['has_wait_send'] = true;
            }else{
                $list[$k]['has_wait_send'] = false;
            }
        }else{
            $list[$k]['has_wait_send'] = false;
        }
    }
    $total = $page_total;
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/sms/sms_template', $return_clicent);
}
//获取短信模版待发送短信数
if ($op=='template_wait_total'){
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        show_json(0,['msg'=>'短信模版参数缺失']);
    }else{
        $item_type_key = '';
        $item = Sms_mod::getSmsTemplateItem($themeid,$template_id);
        if ($item['type']=='quick' || $item['type']=='default'){
            $item_type_key = 'diy_'.$item['id'];
        }
        $sql = " select count(*) as cnt from ".tablename(t_sms_quick_mobile)." where themeid='$themeid' and template_id='$template_id' ";
        $total = (int)db_find($sql)['cnt'];
        $total_txt = "0 /".$total;
        $send_num = ceil($total/100);
        return show_json(1,['count'=>$total,'total_txt'=>$total_txt,'send_num'=>$send_num,'item_type_key'=>$item_type_key]);
    }
}
//获取队列中的待发送手机号 快捷模版中
if ($op=='quick_sms_send'){
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        return show_json(0,['msg'=>'短信模版参数缺失']);
    }
    $res = Sms_mod::quickLlSmsSend($themeid,$system,$template_id);
    if ($res['status']==1){
        return show_json(1,['msg'=>'发送成功','success_total'=>$res['success_total'],'fail_total'=>$res['fail_total']]);
    }else{
        return show_json(0,['msg'=>'发送失败']);
    }
}
//申请短信模版页面
if ($op=='template_add'){
    $sign_name = '易宣';
    if ($_G['companyname'] =='飞驰软件'){
        $sign_name = '飞驰';
    }elseif ($_G['companyname'] =='金策软件'){
        $sign_name = '金策';
    }elseif ($_G['companyname'] =='联登科技'){
        $sign_name = '联登';
    }
    $mobile_bg_img = 'https://css2020.yixuan.net/2020css/yx2020/sms/phone-preview2.svg';
    $mobile_msg_img = 'https://css2020.yixuan.net/2020css/yx2020/sms/phone-msg.svg';
    $action = 9;
    $no_pass_tips = '';
    $template_id = $_P['template_id']?$_P['template_id']:0;
    if ($template_id){
        $item = Sms_mod::getSmsTemplateItem($themeid,$template_id);
        if ($item['template_status']==2){
            //查找最新一条审核日志
            $log_item = db_get(t_sms_template_log,['template_code'=>$item['template_code'],'type'=>4]);
            if ($log_item){
                $no_pass_tips = $log_item['des'];
            }
        }
    }

    $template_type_list = [
        ['title'=>'验证码','key'=>0],
        ['title'=>'短信通知','key'=>1],
        ['title'=>'推广短信','key'=>2],
    ];
    $return_clicent = get_defined_vars();
return view('/sms/sms_betch_llsend', $return_clicent);
}
//快捷发送
if ($op=='quick_sms'){
        $action =1;
        $template_id = isset($_P['template_id'])?$_P['template_id']:0;
        if ($template_id){
            $mobile_str ='';
            $query_item = db_get(t_sms_template,['themeid'=>$themeid,'type'=>'quick','id'=>$template_id]);
            if ($query_item){
                $wait_item = $query_item;
                $mobile_arr = Sms_mod::getQuickMobileList($themeid,$query_item['id']);
                if ($mobile_arr){
                    foreach ($mobile_arr as $k => $v){
                        $mobile_str.= $v['mobile'].PHP_EOL;
                    }
                }
            }
            $return_clicent = get_defined_vars();
return view('/sms/sms_quick_ali_edit', $return_clicent);
            die();
        }
        $oem_str = mb_substr($_G['companyname'], 0, 2);
        $llcurrency = Sms_mod::llCurrency($oem_str);
        foreach ($llcurrency as $index => $item) {
            $llcurrency[$index]['head'] = explode('{', $item['text'])[0];
            $llcurrency[$index]['tail'] = explode('}', $item['text'])[1];
        }
        $sign_name = '【' . $oem_str . '】';

        $mobile_bg_img = 'https://css2020.yixuan.net/2020css/yx2020/sms/phone-preview2.svg';
        $mobile_msg_img = 'https://css2020.yixuan.net/2020css/yx2020/sms/phone-msg.svg';

        $has_system_input_flag = false;

        //动态表单判断
        if ($config['address'] && ($config['addresstype']==2 || $config['addresstype']==3)){
            $get_adress_arr = $config['addressoptions'];
            if ($get_adress_arr && count($get_adress_arr)>0){
                foreach ($get_adress_arr as $k => $v){
                    $tmp_item = ['title'=>$config['address'].'-'.$v,'val'=>'address_'.$k,'type'=>'form'];
                    array_push($sms_system_mobile_type,$tmp_item);
                }
            }
        }
        if ($config['formtwo'] && ($config['formtwotype']==2 || $config['formtwotype']==3)){
            $get_formtwo_arr = $config['formtwooptions'];
            if ($get_formtwo_arr && count($get_formtwo_arr)>0){
                foreach ($get_formtwo_arr as $k => $v){
                    $tmp_item = ['title'=>$config['formtwo'].'-'.$v,'val'=>'formtwo_'.$k,'type'=>'form'];
                    array_push($sms_system_mobile_type,$tmp_item);
                }
            }
        }
        if ($config['shops'] && ($config['shopstype']==0 || $config['shopstype']==3)){
            $get_shops_arr = $config['options'];
            if ($get_shops_arr && count($get_shops_arr)>0){
                foreach ($get_shops_arr as $k => $v){
                    $tmp_item = ['title'=>$config['shops'].'-'.$v,'val'=>'shops_'.$k,'type'=>'form'];
                    array_push($sms_system_mobile_type,$tmp_item);
                }
            }
        }
        //开启订单核销
        if ($config['ishexiao']==1){
            $tmp_item = ['title'=>'订单-未核销','val'=>'wait_hexiao','type'=>'wait_hexiao'];
            array_push($sms_system_mobile_type,$tmp_item);
        }
        if ($config['ishexiao']==1){
            $tmp_item = ['title'=>'订单-已核销','val'=>'has_hexiao','type'=>'has_hexiao'];
            array_push($sms_system_mobile_type,$tmp_item);
        }
        //客资手机号
        $wait_active_customer_total = (int)db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_fans ) . " as f 
                     WHERE f.themeid = '{$themeid}' 
                     and f.username='' and f.mobile!='' and f.nickname!='微信用户'" );
        if ($wait_active_customer_total>0){
            $tmp_item = ['title'=>'粉丝-客资用户','val'=>'wait_active_customer','type'=>'wait_active_customer'];
            array_push($sms_system_mobile_type,$tmp_item);
        }
        $search_start = db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
        $search_start = strtotime(date('Y-m-d 00:00:00',$search_start));
        $search_end = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
        foreach ( $sms_system_mobile_type as $index => $item) {
            $resal = Sms_mod::filteratePhone ($config,$themeid,$item['val'],$item['type']);
            $sms_system_mobile_type[$index]['count'] = $resal['total'];
        }

        $return_clicent = get_defined_vars();
return view('/sms/sms_quick_ali', $return_clicent);
}
//快捷模版修改
if ($op=='quick_sms_edit'){
    if ($open_yx_sms==0){
        show_json(0,['msg'=>'【 短信通知未开通 】 开通请到 "群发短信" => "短信配置" 中开启，如有疑问请联系客服！']);
    }
    //获取原始数据
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        show_json(0,['msg'=>'当前短信模版不可修改']);
    }
    $old_item = db_get(t_sms_template,['themeid'=>$themeid,'type'=>'quick','id'=>$template_id]);
    if (!$old_item){
        show_json(0,['msg'=>'当前短信模版已被删除']);
    }
    //插入新数据
    $mobile_list = $_P['mobile_list']?$_P['mobile_list']:'';
    $quick_template = $_P['quick_template']?$_P['quick_template']:'';
    $remark = $_P['remark']?$_P['remark']:'';
    $temp = mb_substr($remark,0,12,'UTF-8');
    $template_name = isset($temp)?$temp.MODULE_NAME.'_'.date(ymdHi):'快捷模版'.MODULE_NAME.'_'.date(ymdHi);
    $out_template_name = $template_name = mb_substr($template_name,0,30,'utf-8');
    $admin_name = (string)$_G['username'];
    $ip = (string)$_G['clientip'];
    //创建快捷短信模版
    $data = [
        'template_type'=>1,
        'template_name'=>$template_name,
        'out_template_name'=>$out_template_name,
        'template_content'=>$quick_template,
        'out_template_content'=>$quick_template,
        'remark'=>$remark,
        'diy_template_params'=>'',
        'show_template_params'=>'',
        'admin_name'=>$admin_name,
        'ip'=>$ip,
        'themeid'=>$themeid,
    ];
    $res = Sms_mod::addSmsTemplate(1,$template_name,$quick_template,$remark);
    yxlog('快捷短信模版创建：'.json_encode($res),'短信模版');
    if ($res && $res['status']==200){
        $log_data = ['type'=>1,'template_code'=>$res['template_code'],
            'request_params'=>json_encode($data),
            'response_params'=>json_encode($res),
            'des'=>'创建短信模版',
            'admin_name'=>$admin_name,
            'ip'=>$ip,
            'themeid'=>$themeid,
        ];
        Sms_mod::addSmsTemplateLog($log_data);

        $data['template_code'] = $res['template_code'];
        $data['request_id'] = $res['request_id'];
        $data['template_status'] = 0;
        $data['module_name'] = $module_name;
        $data['type'] = 'quick';

        $res1 = $insertid = db_insert(t_sms_template,$data);
        if ($res1){
            $template_id = $insertid;
            $mobile_arr =explode(',',$mobile_list);
            $add_str = '';
            if ($mobile_arr){
                foreach ($mobile_arr as $k => $v){
                    if ($v){
                        $add_str.= "(".$template_id.",".$v.",".$themeid.",'".$admin_name."','".$ip."'),";
                    }
                }
                if ($add_str){
                    $add_str = rtrim($add_str,',');
                    $res2 = Sms_mod::addQuickMobile($add_str);
                }
            }
            //删除原始数据
            $delete_old_item_ali = Sms_mod::deleteSmsTemplate($old_item['template_code']);
            $delete_old_item_= db_delete(t_sms_template,['id'=>$old_item['id'],'themeid'=>$themeid]);
            $delete_old_item_mobile_= db_delete(t_sms_quick_mobile,['template_id'=>$old_item['id'],'themeid'=>$themeid]);
            yxlog('快捷短信手机号录入'.json_encode($mobile_list),'短信模版');
            show_json(1,['msg'=>'操作成功，等待审核中']);
        }else{
            yxlog('短信模版创建失败：'.json_encode($data),'短信模版');
            show_json(0,['msg'=>'短信模版修改失败，请联系管理员']);
        }
    }else{
        show_json(0,['msg'=>'短信运营商通信异常，请联系管理员']);
    }

}
//测试短信模版发送
if ($op=='test_sms_send'){
    $acc= $_P['acc']?$_P['acc']:'display';
    if ($acc=='display'){
        $test_mobile = $_P['mobile']?$_P['mobile']:'';
        $test_template = db_get(t_sms_template,['themeid'=>$themeid,'type'=>'quick','module_name'=>$module_name,'template_status'=>1,'send_all_mobile'=>0]);
        if (!$test_mobile){
            show_json(0,['msg'=>'测试短信接收手机号不合法']);
        }
        if (!$test_template){
            show_json(0,['msg'=>'快捷短信模版不存在']);
        }
        $tmp_code = $test_template['template_code'];
        $res1 = Sms_mod::beforeAliSmsSend($system,$themeid,$test_mobile,$tmp_code,$test_template['id'],'');
        //修改短信模版为已测试未确认
        $data = ['confirm_test_sms'=>1];
        $where = ['id'=>$test_template['id']];
        $res2 = db_update(t_sms_template,$data,$where);
        show_json(1,['msg'=>'发送成功']);
    }else{
        $test_template = db_get(t_sms_template,['themeid'=>$themeid,'type'=>'quick','module_name'=>$module_name,'template_status'=>1]);
        $data = ['confirm_test_sms'=>2];
        $where = ['id'=>$test_template['id']];
        $res2 = db_update(t_sms_template,$data,$where);
        show_json(1,['msg'=>'确认成功，请在页面刷新后点击【确认无误，批量发送】']);
    }

}
//确认短信发送 进行批量发送
if ($op=='sure_quick_sms'){
    //获取所有待发送手机号
    $test_template = db_get(t_sms_template,['themeid'=>$themeid,'type'=>'quick','module_name'=>$module_name,
        'template_status'=>1,'confirm_test_sms'=>2,'send_all_mobile'=>0]);
    if ($test_template){
        $ids = '';
        $mobile_list = db_getall(t_sms_quick_mobile,['themeid'=>$themeid,'template_id'=>$test_template['id']]);
        $mobile_arr = [];
        $template_param_arr = [];
        foreach ($mobile_list as $k => $v){
            array_push($mobile_arr,$v['mobile']);
            array_push($template_param_arr,[]);
            $ids.= $v['id'].',';
        }
        Sms_mod::beforeAliSmsSend($system,$themeid,$mobile_arr,$test_template['template_code'],$test_template['id'],$template_param_arr);
        $data = ['send_all_mobile'=>1];
        $where = ['id'=>$test_template['id']];
        $res2 = db_update(t_sms_template,$data,$where);
        $sql = " delete from ".tablename(t_sms_quick_mobile)." where themeid=$themeid and id in ( ".$ids." ) ";
        db_find($sql);
        show_json(1,['msg'=>'发送成功']);
    }
    show_json(0,['msg'=>'快捷发送失败']);
}
//高级短信模版批量发送
if ($op=='betch_ali'){
    $action = 2;
    //    首次录入
    if ($_G['ispost']){
        if ($open_yx_sms==0){
            show_json(0,['msg'=>' 【 短信通知未开通 】 开通请到 "群发短信" => "短信配置" 中开启，如有疑问请联系客服！']);
        }
        $template_id = $_P['template_id'];
        if (!$template_id){
            show_json(0,['msg'=>'请选择短信模版']);
        }
        $order_list = $order_list_str = preg_replace('/(\")/', '',htmlspecialchars_decode($_P['order_list']));
        $order_list = explode(PHP_EOL,$order_list);
        $order_list_new = [];
        $mobile_arr = [];
        $batch_str = '';//批量插入
        $all_argments = [];
        $char = "/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/";
        $order_list_txt = '';
        $template_item = db_get(t_sms_template,['themeid'=>$themeid,'module_name'=>$module_name,'id'=>$template_id]);
        $diy_template_params = [];
        if ($template_item['diy_template_params']){
            $diy_template_params = explode(',',$template_item['diy_template_params']);
        }
        $flag_mobile_arr = [];
        $can_send_order_list = [];
        $err_tips='';
        if (!$diy_template_params){
            $regMobile = '/[1][3-9]\d{9}/';
            preg_match_all($regMobile,$order_list_str,$result);
            $mobile_arr = [];
            if($result[0]){
                $mobile_arr = $result[0];
            }
        }else{
            foreach ($order_list as $index=>$item){
                $item = trim($item);
                if (!$item){
                    unset($order_list[$index]);
                    continue;
                }
                $tmp_str = preg_replace('/\s+/',',',$item);
                if(strstr($item,'；')){
                    $tmp_str = str_replace('；', ',', $item);
                }
                if(strstr($item,'，')){
                    $tmp_str = str_replace('，', ',', $item);
                }
                if(strstr($item,'|')){
                    $tmp_str = str_replace('|', ',', $item);
                }
                if(strstr($item,'、')){
                    $tmp_str = str_replace('、', ',', $item);
                }
                if(strstr($item,'|')){
                    $tmp_str = str_replace('|', ',', $item);
                }
                if(strstr($item,';')){
                    $tmp_str = str_replace(';', ',', $item);
                }
                $tmp_str = rtrim($tmp_str);
                $temp_arr = explode(',',$tmp_str);
                if ($diy_template_params){
                    if (count($diy_template_params) != (count($temp_arr)-1) ){
                        $err_tips = $item[0].'【输入信息缺失】';
                        break;
                    }else{
                        $insert_des = [];
                        foreach ($diy_template_params as $dpk => $dpv){
                            $insert_des[$dpv] = $temp_arr[$dpk+1];
                        }
                        $tmp_mobile  = $temp_arr[0];
                        if ($tmp_mobile && !in_array($tmp_mobile,$flag_mobile_arr)){
                            array_push($all_argments,$insert_des);
                            array_push($mobile_arr,$tmp_mobile);
                            array_push($flag_mobile_arr,$tmp_mobile);
                            array_push($can_send_order_list,$item);
                        }
                    }
                }
            }
        }
        if ($err_tips){
            show_json(0,['msg'=>$err_tips]);
        }
        $mobile_arr = array_unique($mobile_arr);

        $bufa = count($order_list);
        $chongfu = count($order_list) - count($mobile_arr);
        if (empty($mobile_arr)){
            show_json(0,['msg'=>'请输入正确的信息']);
        }
        foreach ($mobile_arr as $kk => $vv){
            if (!$vv){
                unset($mobile_arr[$kk]);
            }
        }
        $tips='删除：';
        if ($chongfu>0){
            if ($chongfu>0){
                $tips .= '重复手机号'.$chongfu.'个，请确认后点击底部【确认提交】按钮';
            }
            $show_order_list_txt = '';
            foreach ($can_send_order_list as $k => $v){
                $show_order_list_txt.= $v.PHP_EOL;
            }
            show_json(0,['msg'=>$tips,'list'=>$show_order_list_txt]);
        }
        //判断是简单模版还是高级模版
        //判断数量
        if ($template_item['type']=='quick'){
//            if (count($mobile_arr)<1000){
            if (count($mobile_arr)<1){
                Sms_mod::beforeAliSmsSend($system,$themeid,$mobile_arr,$template_item['template_code'],$template_item['id'],$all_argments);
                show_json(1,['msg'=>'正在执行中，请等待。。。','type'=>'auto_send','template_type'=>'quick','template_id'=>$template_id]);
            }else{
                //压入队列
                Sms_mod::pushSmsSendQueue($system,$themeid,$mobile_arr,$template_item['template_code'],$template_item['id'],$all_argments);
                show_json(1,['msg'=>'批量处理成功，等待执行队列','type'=>'wait_queue','template_type'=>'quick','template_id'=>$template_id]);
            }
        }else{
//            if (count($mobile_arr)<100){
            if (count($mobile_arr)<1){
                Sms_mod::beforeAliSmsSend($system,$themeid,$mobile_arr,$template_item['template_code'],$template_item['id'],$all_argments);
                show_json(1,['msg'=>'正在执行中，请等待。。。','type'=>'auto_send','template_type'=>'default','template_id'=>$template_id]);
            }else{
                //压入队列
                Sms_mod::pushSmsSendQueue($system,$themeid,$mobile_arr,$template_item['template_code'],$template_item['id'],$all_argments);
                show_json(1,['msg'=>'批量处理成功，等待执行队列','type'=>'wait_queue','template_type'=>'default','template_id'=>$template_id]);
            }
        }

    }
    $template_id = $_P['template_id']?$_P['template_id']:0;
    $item = [];
    $demo_txt = '170xxxx8766,';
    $notice_txt = '';
    $format_item_out_template_content = '';
    $name_arr = ['张三','李四','王五'];
    $desc_arr = ['梦幻大礼包','体验课程一节','备注：不退不换'];
    $address_arr = ['大融城一号门','银座中心3楼','新地标4号门'];
    $shop_arr = ['巴拉巴拉大融城店','胡琦贝尔银座中心店','新地标店'];
    $time_arr = ['10月1日','9月2日17点','3月12日上午10点'];
    $money_arr = ['9.9','137.5','77.32'];

    $item_type_key = '';
    $once_notice = '13123452345';
    $more_notice = '18856785678';
    if ($template_id){
        $action =5;
        $item = Sms_mod::getSmsTemplateItem($themeid,$template_id);
        if ($item['type']=='quick' || $item['type']=='default'){
            $item_type_key = 'diy_'.$item['id'];
        }
        $format_item_out_template_content = str_replace("#",'',$item['out_template_content']);
        if ($item['diy_template_params']){
            $diy_filed_arr = explode(',',$item['diy_template_params']);
            foreach ($diy_filed_arr as $k => $v){
                if (strpos($v,'name_') !== false){
                    $once_notice.=',张三';
                    $more_notice.=',李四';
                    $name_tmp_val = $name_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$name_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $name_tmp_val.',';
                }elseif (strpos($v,'address_')!==false){
                    $once_notice.=',地址1';
                    $more_notice.=',地址2';
                    $address_tmp_val = $address_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$address_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $address_tmp_val.',';
                }elseif (strpos($v,'shop_')!==false){
                    $once_notice.=',店名1';
                    $more_notice.=',店名2';
                    $shop_tmp_val = $shop_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$shop_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $shop_tmp_val.',';
                }elseif (strpos($v,'time_')!==false){
                    $once_notice.=',时间1';
                    $more_notice.=',时间2';
                    $time_tmp_val = $time_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$time_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $time_tmp_val.',';
                }elseif (strpos($v,'money_')!==false){
                    $once_notice.=',10元';
                    $more_notice.=',20元';
                    $money_tmp_val = $money_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$money_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $money_tmp_val.',';
                }else{
                    $desc_tmp_val = $desc_arr[rand(0,2)];
                    $format_item_out_template_content = str_replace($v,$desc_tmp_val,$format_item_out_template_content);
                    $demo_txt.= $desc_tmp_val.',';
                }
            }
        }
        $more_notice = $once_notice.'<br/>'.$more_notice;
        $demo_txt = rtrim($demo_txt,',');
    }
    $list =  Sms_mod::getSmsTemplate($themeid,$search_data,0,0,1,'',false);
    $total = count($list);

    $has_system_input_flag = false;

    //动态表单判断
    if ($config['address'] && ($config['addresstype']==2 || $config['addresstype']==3)){
        $get_adress_arr = $config['addressoptions'];
        if ($get_adress_arr && count($get_adress_arr)>0){
            foreach ($get_adress_arr as $k => $v){
                $tmp_item = ['title'=>'表单文本2-'.$v,'val'=>'address_'.$k,'type'=>'form'];
                array_push($sms_system_mobile_type,$tmp_item);
            }
        }
    }
    if ($config['formtwo'] && ($config['formtwotype']==2 || $config['formtwotype']==3)){
        $get_formtwo_arr = $config['formtwooptions'];
        if ($get_formtwo_arr && count($get_formtwo_arr)>0){
            foreach ($get_formtwo_arr as $k => $v){
                $tmp_item = ['title'=>'表单文本3-'.$v,'val'=>'formtwo_'.$k,'type'=>'form'];
                array_push($sms_system_mobile_type,$tmp_item);
            }
        }
    }
    if ($config['shops'] && ($config['shopstype']==0 || $config['shopstype']==3)){
        $get_shops_arr = $config['options'];
        if ($get_shops_arr && count($get_shops_arr)>0){
            foreach ($get_shops_arr as $k => $v){
                $tmp_item = ['title'=>'表单文本5-'.$v,'val'=>'shops_'.$k,'type'=>'form'];
                array_push($sms_system_mobile_type,$tmp_item);
            }
        }
    }
    //非异业模式并且开启订单核销
    if ($system['softstyle']<=6 && $config['ishexiao']==1){
        $tmp_item = ['title'=>'订单-待核销','val'=>'wait_hexiao','type'=>'wait_hexiao'];
        array_push($sms_system_mobile_type,$tmp_item);
    }
    //客资手机号
    $wait_active_customer_total = (int)db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename ( t_fans ) . " as f 
                     WHERE f.themeid = '{$themeid}' 
                     and f.username='' and f.mobile!='' and f.nickname!='微信用户'" );
    if ($wait_active_customer_total>0){
        $tmp_item = ['title'=>'客资用户','val'=>'wait_active_customer','type'=>'wait_active_customer'];
        array_push($sms_system_mobile_type,$tmp_item);
    }

    $search_start = db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
    $search_start = strtotime(date('Y-m-d 00:00:00',$search_start));
    $search_end = mktime(23, 59, 59, date('m'), date('d'), date('Y'));

    $return_clicent = get_defined_vars();
return view('/sms/sms_betch_ali', $return_clicent);
}

//通过系统内检索条件去匹配手机号
if ($op=='betch_ali_match'){
    $mobile_type = isset($_P['mobile_type'])?$_P['mobile_type']:'';
    $mobile_type_type = isset($_P['mobile_type_type'])?$_P['mobile_type_type']:'';
    $start_time = isset($_P['start_time'])?strtotime($_P['start_time']):'';
    $end_time = isset($_P['end_time'])?strtotime($_P['end_time']):'';
    if (!$mobile_type){
        return show_json(0,['msg'=>'客户分类为空']);
        die();
    }
//    if (!$start_time){
//        return show_json(0,['msg'=>'开始时间为空']);
//        die();
//    }
//    if (!$end_time){
//        return show_json(0,['msg'=>'结束时间为空']);
//        die();
//    }
    $response = Sms_mod::filteratePhone ($config,$themeid,$mobile_type,$mobile_type_type,$start_time,$end_time);
    return show_json(1,['msg'=>'匹配成功','data'=>$response]);
}
//短信模版执行批量发送队列
if ($op=='template_queue_wait_total'){
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        show_json(0,['msg'=>'短信模版参数缺失']);
    }else{
        $template_item = db_get(t_sms_template,['themeid'=>$themeid,'id'=>$template_id]);


        $item_type_key = '';
        if ($template_item['type']=='quick' || $template_item['type']=='default'){
            $item_type_key = 'diy_'.$template_item['id'];
        }

        $sql = " select count(*) as cnt from ".tablename(t_sms_wait_send_queue)." where themeid='$themeid' and templateId='$template_id' ";
        $total = (int)db_find($sql)['cnt'];
        $total_txt = "0 /".$total;
        $template_type_limit = 100;
        if ($template_item['type']!='quick'){
            $template_type_limit = 100;
        }
        $send_num = ceil($total/$template_type_limit);
        return show_json(1,['count'=>$total,'total_txt'=>$total_txt,'send_num'=>$send_num,'item_type_key'=>$item_type_key]);
    }
}
//执行队列中短信模版发送
if ($op=='queue_sms_template_send'){
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        return show_json(0,['msg'=>'短信模版参数缺失']);
    }
    $res = Sms_mod::sendSmsQueueByTemplateId($themeid,$system,$template_id);
    if ($res['status']==1){
        return show_json(1,['msg'=>'发送成功','success_total'=>$res['success_total'],'fail_total'=>$res['fail_total']]);
    }else{
        return show_json(0,['msg'=>'发送失败','success_total'=>$res['success_total'],'fail_total'=>$res['fail_total']]);
    }
}
//取消队列发送
if ($op=='delete_queue_sms'){
    $template_id = isset($_P['template_id'])?$_P['template_id']:0;
    if (!$template_id){
        return show_json(0,['msg'=>'短信模版参数缺失']);
    }
    $res = db_delete(t_sms_wait_send_queue,['themeid'=>$themeid,'templateId'=>$template_id]);
    if ($res){
        return show_json(1,['msg'=>'取消发送成功']);
    }else{
        return show_json(0,['msg'=>'取消发送失败']);
    }
}
//手机号唯一性验证
if ($op=='check_mobile'){
    $mobile_list = $_P['mobile_list']?$_P['mobile_list']:$_P['order_list'];

    $regMobile = '/[1][3-9]\d{9}/';
    preg_match_all($regMobile,$mobile_list,$result);
    $mobile_arr = [];
    if($result[0]){
        $mobile_arr = $result[0];
    }

    $chongfu = count($mobile_arr);
    $mobile_arr = array_unique($mobile_arr);
    $chongfu = $chongfu-count($mobile_arr);
    $sure = count($mobile_arr);
    $mobile_txt = implode(',',$mobile_arr);

    $msg = '手机号核验完成,';
    if ($chongfu>0){
        $msg .= '删除重复手机号'.$chongfu.'个,';
    }
    $msg .= '可发送手机号'.$sure.'个.';
    show_json(1,['msg'=>$msg,'data'=>['chongfu'=>$chongfu,'sure'=>$sure,'mobile_txt'=>$mobile_txt]]);
}
//短信内容审核
if ($op=='audio_sms_content'){
    $content = $_P['content'];
    $res = Sms_mod::checkStrSafe($content);
    show_json(1,['msg'=>'处理成功','data'=>$res]);
}

//高级短信模版编辑
if ($op=='template_edit'){

    $template_id = $_P['template_id']?$_P['template_id']:0;
    $template_type = trim($_P['template_type']);
    $temp = mb_substr(trim($_P['remark']),0,8,'UTF-8');
    $out_template_name = $template_name = $_P['template_name']?$_P['template_name']:$temp.MODULE_NAME.'_'.date(ymdHi);
    $template_name = mb_substr($template_name,0,30,'utf-8');
    $template_content = trim($_P['template_content']);
    $out_template_content = trim($_P['out_template_content']);
    $diy_template_params = trim($_P['diy_template_params']);
    $show_template_params = trim($_P['show_template_params']);
    $remark = trim($_P['remark']);
    if (!$out_template_name || $template_name){
        $out_template_name = $template_name = $temp.MODULE_NAME.'_'.date(ymdHi);
    }
    if (!$template_type){
        show_json(0,['msg'=>'短信类型未选择']);
    }
    if (!$out_template_name){
        show_json(0,['msg'=>'短信模版名称未填写']);
    }
    if (!$template_content || !$out_template_content){
        show_json(0,['msg'=>'短信模版内容未填写']);
    }
    if (!$remark){
        show_json(0,['msg'=>'短信模版申请说明未填写']);
    }
    if ($template_type==2){
        $template_content = $template_content." ".'拒收请回复R';
        $out_template_content = $out_template_content." ".'拒收请回复R';
    }
    //查询是否有重名申请短信模版
    if (!$template_id){
        $check_item = db_get(t_sms_template,['themeid'=>$themeid,'template_name'=>$template_name,'module_name'=>$module_name]);
    }else{
        $sql = " select id from ".tablename(t_sms_template)." where module_name='$module_name' and themeid=$themeid and template_name='$template_name' and id!=$template_id ";
        $check_item = db_find($sql);
    }

    if ($check_item){
        show_json(0,['msg'=>'该模版名称已存在，请检查后重新申请']);
    }

    //todo 添加模版以及日志

   // $out_template_content =
    $data = [
        'template_type'=>$template_type,
        'template_name'=>$template_name,
        'out_template_name'=>$out_template_name,
        'template_content'=>$template_content,
        'out_template_content'=>$out_template_content,
        'remark'=>$remark,
        'diy_template_params'=>$diy_template_params,
        'show_template_params'=>$show_template_params,
        'admin_name'=>$_G['username'],
        'ip'=>$_G['clientip'],
        'themeid'=>$themeid,
    ];
    yxlog('参数：'.json_encode($data),'短信模版');
    if (!$template_id){
        $res = Sms_mod::addLlSmsTemplate($template_type,$template_name,$template_content,$remark);
        //$res = Sms_mod::addSmsTemplate($template_type,$template_name,$template_content,$remark);
        yxlog('创建：'.json_encode($res),'联麓短信模版');
    }else{
        $item = db_get(t_sms_template,['themeid'=>$themeid,'id'=>$template_id]);
        $res = Sms_mod::editLlSmsTemplate($template_type,$template_name,$item['template_code'],$template_content,$remark);
        yxlog('更新：'.json_encode($res),'短信模版');
    }

    if ($res['status']==200){
        $log_data = ['type'=>1,'template_code'=>$res['template_code'],
            'request_params'=>json_encode($data),
            'response_params'=>json_encode($res),
            'des'=>'创建短信模版',
            'admin_name'=>$_G['username'],
            'ip'=>$_G['clientip'],
            'themeid'=>$themeid,
        ];
        if ($template_id){
            $log_data['type']=2;
            $log_data['des']='修改短信模版重新审核';
        }
        Sms_mod::addSmsTemplateLog($log_data);
        $data['template_code'] = $res['template_code'];
        $data['request_id'] = $res['request_id'];
        $data['template_status'] = 0;
        $data['module_name'] = $module_name;
        if (!$template_id){
            $insertid = db_insert(t_sms_template,$data);
        }else{
            db_update(t_sms_template,$data,['id'=>$template_id]);
        }

        show_json(1,['msg'=>'操作成功']);
    }else{
        show_json(0,['msg'=>'操作失败，请联系管理员']);
    }
}

//查询短信模版
if ($op=='template_query'){
    $template_id = $_P['template_id']?$_P['template_id']:0;
    if (!$template_id){
        show_json(0,['msg'=>'短信模版参数缺失']);
    }
    $item = db_get(t_sms_template,['themeid'=>$themeid,'id'=>$template_id,'module_name'=>$module_name]);
    $template_code = $item['template_code'];
    $res = Sms_mod::querySmsTemplate($template_code);
    yxlog('短信模版状态查询：'.json_encode($res),'短信模版');
    if ($res['status']==200){
        $log_data = [
            'template_code'=>$item['template_code'],
            'request_params'=>json_encode(['template_code'=>$template_code]),
            'response_params'=>json_encode($res),
            'admin_name'=>$_G['username'],
            'themeid'=>$themeid,
        ];

        if ($res['template_status']==0){
            show_json(0,['当前模版在审核中请耐心等待']);
        }elseif ($res['template_status']==1){
            $log_data['type']=3;
            $log_data['des']='审核通过';
            Sms_mod::addSmsTemplateLog($log_data);

            $where = ['themeid'=>$themeid,'id'=>$template_id];
            $data = ['request_id'=>$res['request_id'],'template_status'=>1];
            db_update(t_sms_template,$data,$where);
        }elseif ($res['template_status']==2){
            $log_data['type']=4;
            $log_data['des']='审核未通过，原因：'.$res['reason'];
            Sms_mod::addSmsTemplateLog($log_data);
            $where = ['themeid'=>$themeid,'id'=>$template_id];
            $data = ['request_id'=>$res['request_id'],'template_status'=>2];
            db_update(t_sms_template,$data,$where);
        }
    }
    show_json(0,['当前模版在审核中请耐心等待']);
}
//删除短信模版
if ($op=='template_delete'){
    $template_id = $_P['template_id']?$_P['template_id']:0;
    if (!$template_id){
        show_json(0,['msg'=>'短信模版参数缺失']);
    }
    $item = db_get(t_sms_template,['themeid'=>$themeid,'id'=>$template_id]);
    $template_code = $item['template_code'];
    $res = Sms_mod::deleteSmsTemplate($template_code);
    yxlog('执行删除：'.json_encode($item),'短信模版');
    if ($res['status']==200){
        yxlog('删除成功：'.json_encode($res),'短信模版');
    }else{
        yxlog('删除失败：'.json_encode($res),'短信模版');
    }
}
//个性短信发送
if($op=='personal_send'){

        Sms_mod::installSql();
        $template_id = $_P['template_id']?$_P['template_id']:0;
        $template_type = trim($_P['template_type'])?trim($_P['template_type']):2;
        $temp = mb_substr(trim($_P['remark']),0,8,'UTF-8');
        $out_template_name = $template_name = $_P['template_name']?$_P['template_name']:$temp.MODULE_NAME.'_'.date(ymdHi);
        $template_name = mb_substr($template_name,0,30,'utf-8');
        $template_content = trim($_P['template_content']);
        $out_template_content = trim($_P['out_template_content']);
        $diy_template_params = trim($_P['diy_template_params']);
        $show_template_params = trim($_P['show_template_params']);
       // $remark = trim($_P['remark']);
        $delayed_send = trim($_P['delayed_send']);
        $delayed_time = trim($_P['delayed_time'])?trim($_P['delayed_time']):0;
        $order_list = $_P['order_list'];
        $quick_cols = $_P['quick_cols'];

        if (!$out_template_name || $template_name){
            $out_template_name = $template_name = $temp.MODULE_NAME.'_'.date(ymdHi);
        }
        if (!$template_type){
            show_json(0,['msg'=>'短信类型未选择']);
        }
        if (!$out_template_name){
            show_json(0,['msg'=>'短信模版名称未填写']);
        }
        if (!$template_content || !$out_template_content){
            show_json(0,['msg'=>'短信模版内容未填写']);
        }
//        if (!$remark){
//            show_json(0,['msg'=>'短信模版申请说明未填写']);
//        }
        if($delayed_send==1){
            if(!$delayed_time){
                show_json(0,['msg'=>'请选择定时发送时间']);
            }
            $is_date = strtotime($delayed_time) ? strtotime($delayed_time) : false;
            if($is_date===false){
                show_json(0,['msg'=>'定时发送时间格式不正确']);
            }
            $time = strtotime($delayed_time)-time();
            if($time<(60*10)){//必须大于10分钟
                show_json(0,['msg'=>'定时时间必须大于当前时间10分钟']);
            }
       }

//        if ($template_type==2){
//            $template_content = $template_content." ".'拒收请回复R';
//            $out_template_content = $out_template_content." ".'拒收请回复R';
//        }
        $ParamSet = [];
        $mobile_list = [];
        $mobile_str = '';

        $template_params_array = explode(',',$diy_template_params);
        $param_key = [];
        foreach ($template_params_array as $par){
             $key=array_keys($quick_cols,$par);
             if($key){
                 $param_key[] = $key[0];
             }
        }

        foreach ($order_list as $index=>$item){
            $params = [];
            $mobile_list[] = $item[0];
            $params[] = $item[0];
            foreach ($param_key as $key=>$val){
                $params[] =   $item[$val];
            }
            $ParamSet[] = $params;
            unset($params);
        }
        $TaskTime = Sms_mod::timeStamp13($delayed_time);
        $sms = Sms_mod::llPersonalSend($system,$config,$themeid,$template_content,$mobile_list,$ParamSet,$TaskTime,'sales');
        if($sms['status']==200){
            show_json(1,['msg'=>'提交成功，正在审核发送中']);
        }else{
            show_json(0,['msg'=>$sms['msg']]);
        }
}

//联麓快捷发送
if ($op == 'll_shortcut') {
    Sms_mod::installSql();
    $themeid = $_P['themeid'];
    $mobile_txt = explode(',', $_P['mobile_txt']);
    $template_params_arr[0] = trim($_P['content']);
    $tail = trim($_P['tail']);
    $timed_transmission = trim($_P['timed_transmission']);
    $fixed_time = trim($_P['fixed_time']);
    $fixed_time1 = trim($_P['fixed_time1']);
    $fixed_time .= ' '.$fixed_time1;
    $fixed_time = Sms_mod::timeStamp13($fixed_time);
    if(empty($_P['mobile_txt'])){
        return_json('0', '手机号码不可为空');
    }
    if(count($mobile_txt)>10000){
        return_json('0', '手机号码超过一万个');
    }
    if(empty($_P['content'])){
        return_json('0', '请填写短信内容');
    }
    if($timed_transmission=='1'){
        if(empty($fixed_time)){
            return_json('0', '请选择定时时间');
        }else{
            $time = round(microtime(true) * 1000);
            $time = $fixed_time-$time;
            if($time<(60000*10)){//必须大于10分钟
                return_json('0', '定时时间必须大于当前时间10分钟');
            }
        }
    }else{
        $fixed_time = '';
    }
    //$content组成部分：签名+变量的前文字+变量的内容+变量的后文字
    $content = trim($_P['content']) . $tail;
    $qianming = '【'.$brand.'】';
    $sms_length = mb_strlen($qianming.$content, 'UTF8');
    $sms_num = ceil($sms_length / 67);
    $admin_name = (string)$_G['username'];
    $ip = (string)$_G['clientip'];
    $data = [];
    if ($sms_length > 350) {
        return_json('0', '短信长度过长,超过350个字符');
    }
    //过滤敏感词
    $checkStrSafe = Sms_mod::checkStrSafe($content);
    if($checkStrSafe['filter_word_count']>0){
        return_json('0', $checkStrSafe['filter_word_log']);
    }

    //判断能否余额是否能抵扣短信费用
    $can_send_sms = Sms_mod::checkCanSendSms($themeid, $sms_num * count($mobile_txt));
    if(!$can_send_sms){
        return_json('0', '账户余额不足,无法抵扣短信费用');
    }

    //处理短信中的英文逗号
    $content = str_replace(',','，',$content);
    //普通短信去除【拒收请回复R】
    $content = str_replace("拒收请回复R", "", $content);
    $des = time().rand(10000,99999);
    foreach ($mobile_txt as $key => $value) {
        $data[$key]['uid'] = 0;
        $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $value]);
        if ($get_order_info) {
            $data[$key]['uid'] = $get_order_info['uid'];
        }
        $data[$key]['mobile'] = $value;
        $data[$key]['type'] = 'llfast';
        $data[$key]['templateKey'] = 'notify';
        $data[$key]['templateId'] = $template_id;
        $data[$key]['sms_num'] = $sms_num;
        $data[$key]['content'] = $content;
        $data[$key]['admin_name'] = $admin_name;
        $data[$key]['ip'] = $ip;
        $data[$key]['themeid'] = $themeid;
        $data[$key]['fixed_time'] = $fixed_time;
        $data[$key]['status'] = 6;
        $data[$key]['des'] = $des;
    }
    $resalt = db_insert_all(t_sms_send_log, $data);
    if (empty($resalt)) {
        return_json('0', 'SQL执行失败');
    }
    $Tag = MODULE_NAME.'-'.$themeid;
    $res = Sms_mod::llNormalSend($mobile_txt,$qianming,$content,$fixed_time,$Tag,'notify');

    if ($res['msg'] == 'success') {
        $TaskId = $res['data']['taskId'];
        $res_y = db_update(t_sms_send_log, ['tradeId'=>$TaskId], array('des' => $des));
        //修改失败后重试三次
        if(empty($res_y)){
            for ($i=1; $i<=3; $i++){
                $res_y1 = db_update(t_sms_send_log, ['tradeId'=>$TaskId], array('des' => $des));
                if($res_y1){
                    break;
                }
                if($i==3){
                    yxlog($TaskId,'短信发送，但写入tradeId失败！');
                }
            }
        }
        return_json('200', '提交成功,正在发送');
    } else {
        db_update(t_sms_send_log, ['status'=>2], array('des' => $des));
        return_json($res['status'], $res['msg']);
    }
}
if($op == 'reissue'){
    $TaskId = $_P['TaskId'];
    $admin_name = (string)$_G['username'];
    $ip = (string)$_G['clientip'];
    if(empty($TaskId)){
        return_msg('TaskId不存在');
    }
    $flog = db_getall(t_sms_send_log, ['tradeId' => $TaskId]);
    if(!empty($flog)){
        return_msg('TaskId的已存在'.count($flog).'个号码');
    }
    $post_url = 'https://apis.shlianlu.com/sms/trade/report';
    $params["TaskId"] = $TaskId;
    $params["pageNo"] = 1;
    $params["pageSize"] = 10000;
    $format_json = Sms_mod::llFormatParams($params, 'sales');
    $response = Sms_mod::llPostCurl($format_json, $post_url);
    if ($response['message'] == 'success') {
        $content = '';
        $sms_length = mb_strlen($response['data'][0]['content'], 'UTF8');
        $sms_num = ceil($sms_length / 67);
        $content = str_replace(',','，',$response['data'][0]['content']);
        $qianming = '【'.$brand.'】';
        $content = str_replace($qianming,'',$content);
        foreach ($response['data'] as $key => $value){
            $data[$key]['tradeId'] = $TaskId;
            $data[$key]['mobile'] = $value['phone'];
            $data[$key]['sms_num'] = $sms_num;
            $data[$key]['content'] = $content;
            $data[$key]['fixed_time'] = strtotime($value['respTime'])*1000;
            $data[$key]['created_at'] = $value['respTime'];
            $data[$key]['themeid'] = $_P['themeid'];
            $data[$key]['type'] = 'llfast';
            $data[$key]['trade_status'] = 'DELIVRD';
            $data[$key]['admin_name'] = $admin_name;
            $data[$key]['ip'] = $ip;
        }
        $resalt = db_insert_all(t_sms_send_log, $data);
        if (empty($resalt)) {
            return_msg('sql写入失败');
        }else{
            return_msg('写入成功');
        }
    }else{
        return_msg('请求联麓接口失败'.$response['message']);
    }
}

if($op == 'sendlog'){

    $action = 6;
    $search = $_P['search'];
    if (!db_tableexists(t_sms_send_log)) {
        $return_clicent = get_defined_vars();
return view('/sms/sendlog', $return_clicent);
        die;
    }

    $sql = "select tradeId,content,status,admin_name,ip,created_at,fixed_time,templateKey from yx_".t_sms_send_log." where themeid=".$themeid."  and (type='llfast' or type='senior')  GROUP  BY  tradeId order by id desc ";
    $list = db_select($sql);

    foreach ($list as $key => $value){
        //查询发送成功的
        $success = db_getall(t_sms_send_log,['tradeId'=>$value['tradeId'],'themeid'=>$themeid,'status'=>1],['sms_num','mobile']);
        $fail = db_getall(t_sms_send_log,['tradeId'=>$value['tradeId'],'themeid'=>$themeid,'status'=>2],['sms_num','mobile']);
        $log = db_getall(t_sms_send_log,['tradeId'=>$value['tradeId'],'themeid'=>$themeid],['sms_num','mobile']);
        $list[$key]['count'] = count($log);
        $list[$key]['success'] = count($success);
        $list[$key]['fail'] = count($fail);
        $sum = array_column($success,'sms_num');
        $list[$key]['sum_count'] = array_sum($sum);
        $list[$key]['sum'] = array_sum($sum)*0.1;
        if($value['fixed_time']){
            $fixed_time = $value['fixed_time']/1000;
            $list[$key]['fixed_time'] = date("Y-m-d H:i:s",$fixed_time);
        }
    }
    //即时发送
    $sql = "select sms_num from yx_".t_sms_send_log." where themeid=".$themeid." and status=1 and type!='llfast' and type!='senior'";
    $send_log = db_select($sql);
    if($send_log){
        $sms_num = array_column($send_log,'sms_num');
        $lisa = [
            'tradeId'=>'000000000000000000000',
            'content'=>'即时提醒',
            'status'=>'1',
            'count'=>count($send_log),
            'success'=>count($send_log),
            'fail'=>0,
            'sum_count'=>array_sum($sms_num),
            'sum'=>array_sum($sms_num)*0.1,
            'created_at'=>$config['open_time'],
            'fixed_time'=>date("Y-m-d H:i:s",time()),
        ];
        array_unshift($list,$lisa);
    }

    $return_clicent = get_defined_vars();
return view('/sms/sendlog', $return_clicent);
}
//上传
if($op == 'import'){
    global $_G;
    require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
    require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/IOFactory.php';
    require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/Reader/Excel5.php';
    $path = PATH_MODULE .'data/tmp/';

    if (!is_dir($path)) {
        //load_func('file');
        mkdirs($path);
    }

    $excefile = 'file';
    $filename = $_FILES[$excefile]['name'];
    $tmpname = $_FILES[$excefile]['tmp_name'];
    if (empty($tmpname)) {
        return_msg('请选择要上传的Excel文件!', '', 'error');
    }

    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if (($ext != 'xlsx') && ($ext != 'xls')) {
        return_msg('请上传 xls 或 xlsx 格式的Excel文件!', '', 'error');
    }

    $file = time() . $_G['mpid'] . '.' . $ext;
    $uploadfile = $path . $file;
    $result = move_uploaded_file($tmpname, $uploadfile);

    if (!$result) {
        return_msg('上传Excel 文件失败, 请重新上传!', '', 'error');
    }

    $reader = PHPExcel_IOFactory::createReader($ext == 'xls' ? 'Excel5' : 'Excel2007');
    $excel = $reader->load($uploadfile);
    $sheet = $excel->getActiveSheet();
    $highestRow = $sheet->getHighestRow();
    if($highestRow>10001){
        show_json(0,['msg'=>'最多可上传一万条']);
    }

    $highestColumn = $sheet->getHighestColumn();
    $highestColumnCount = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $values = array();
    //取出第一列
    $row = 1;
    while ($row <= $highestRow) {
            $rowValue = array();
            $col = 0;
            while ($col < $highestColumnCount) {
                $val = $sheet->getCellByColumnAndRow($col, $row)->getValue();
                if($val){
                    $rowValue[] = $val;
                }
                ++$col;
            }
            $values[] = $rowValue;
            ++$row;
    }

    $filed = array_shift($values);
    $table_cols = array();
    $select_data = array();
    foreach ($filed as $k=>$v){
        $table_cols[] = ['field'=>$v,'title'=>$v,'width'=>0];
        $select_data[] = $v;
    }

    $show_value = array_slice($values, 0, 3);
    $table_data  = array();
    foreach ($show_value as  $value){
        if(!empty($value)){
            $new_val = array_combine($filed,$value);
            $table_data[] = $new_val;
        }
    }
    $regMobile = '/[1][3-9]\d{9}/';
    $all_data = [];
    $right_mobile_num = 0;         //正确手机号数量
    $unqualified_mobile_num = 0;   //不合格手机号数量
    $repeatd_mobile_num = 0;       //重复手机号数量
    $mobile_array = [];
    foreach ($values as $key=>$val){
        $mobile = $val[0];
        if(preg_match($regMobile,$mobile)){
            if(!in_array($mobile,$mobile_array)){
                $all_data[] = $val;
                $mobile_array[] = $mobile;
                $right_mobile_num++;
            }else{
                $repeatd_mobile_num++;
            }
        }else{
            $unqualified_mobile_num++;
        }
    }

    $data['table_cols'] = $table_cols;
    $data['all_data'] = $all_data;
    $data['table_data'] = $table_data;
    $data['select_data'] = $select_data;
    $data['right_mobile_num'] = $right_mobile_num;
    $data['unqualified_mobile_num'] = $unqualified_mobile_num;
    $data['repeatd_mobile_num'] = $repeatd_mobile_num;

    show_json(1,['msg'=>'上传成功','data'=>$data]);
}
//金额记录
if($op == 'amount_list'){
    Sms_mod::installSql();
    $type = isset($_P['type'])?$_P['type']:0;
    $action = 11;
    $amount_array = [
        ['title'=>'充值','key'=>1,'total'=>0],
//        ['title'=>'消费','key'=>2,'total'=>0],
        ['title'=>'提现','key'=>3,'total'=>0],
    ];
    $all_total = 0;
    foreach ($amount_array as $k => $v){
        $sql = "SELECT COUNT(*) as total,sum(amount) as sum  from ". tablename(t_sms_amount_record) . "  where themeid='$themeid' and type=".$v['key'];
        $sms_amount = db_find($sql);
        $amount_array[$k]['total'] = $sms_amount['total'];
        $all_total += $sms_amount['total'];
        $amount_array[$k]['sum'] = $sms_amount['sum'];
    }
    array_unshift($amount_array,['title'=>'全部','key'=>0,'total'=>$all_total]);
    $where = "";
    if ($type) {
        $where .= " and type='$type'";
    }
    $sql = "  from " . tablename(t_sms_amount_record) . "  where themeid=$themeid " . $where;
    $count = intval(db_fetchcolumn('SELECT COUNT(*)' . $sql));
    $sql = " select * " . $sql." order by created_at desc LIMIT " . $page_start . "," . $page_size;
    $list =  db_select($sql);
    $total = $count;
    $pager = pagination($count,$page_index,$page_size);
    $sql2 = " select sum(sms_num) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid  and (status=1 or status=6) ";
    $used_amount = db_find($sql2)['cnt']*0.1;
    $amount_total = Sms_mod::getAmountRecordTotal($themeid);
    $return_clicent = get_defined_vars();
return view('/sms/sms_amount', $return_clicent);
}
//金额充值
if($op == 'amount_recharge'){
    if (!$_G['isSuperAdmin'] || DOMAIN1 != "www.yixuan.net" ){
        show_json(0,['msg'=>'当前身份不合法，操作权限受限']);
    }
    $amount  = $_P['amount'];
    $img = $_P['upload_img_url']?$_P['upload_img_url']:'';
    if(empty($amount)){
        show_json(0,['msg'=>'请填写金额']);
    }
    if(empty($img)){
        show_json(0,['msg'=>'请上传凭证']);
    }
    $blance = Sms_mod::addAmountRecord($themeid,1,$amount,'短信充值',$img);
    if($blance['status']==200){
        show_json(1,['msg'=>$blance['msg']]);
    }else{
        show_json(0,['msg'=>$blance['msg']]);
    }
}
//金额提现
if($op == 'amount_cashout'){
    if (!$_G['isSuperAdmin'] || DOMAIN1 != "www.yixuan.net" ){
        show_json(0,['msg'=>'当前身份不合法，操作权限受限']);
    }
    $amount  = $_P['amount'];
    if(empty($amount)){
        show_json(0,['msg'=>'请填写金额']);
    }
    $blance = Sms_mod::addAmountRecord($themeid,3,$amount,'短信余额提现');
    if($blance['status']==200){
        show_json(1,['msg'=>$blance['msg']]);
    }else{
        show_json(0,['msg'=>$blance['msg']]);
    }
}
//图片上传
if ($op=='amount_upload'){
    if (!$_G['isSuperAdmin'] || DOMAIN1 != "www.yixuan.net" ){
        show_json(0,['msg'=>'当前身份不合法，操作权限受限']);
    }
    $r=YxUploadImg($_P);
    if ($r['error']==200){
        $r['remotepath'] = str_replace('http://', 'https://', $r['remotepath']);
        return_json(200,'success',['img_url'=>$r['remotepath']]);
    }
    return_json(100,'上传图片失败',[]);
}
if($op == 'renew'){
    $tradeId = $_P['tradeId'];
    if(empty($tradeId)){
        return_json(0,'任务ID缺失');
    }
    $res = Sms_mod::llReport($system,$tradeId);
    if($res){
        return_json(200,'更新成功');
    }else{
        return_json(0,'更新失败');
    }
}
//手动通知转营销
if($op == 'change_marketing'){
    $themeid = intval($_P['themeid']);
    $system = $_G['system'];
    $input = $_P['__input'];
    $res = Sms_mod::changeMarketing($system,$themeid,$input);
    return $res;
}

}
}